package com.esbi.projectwebsocket.webSocket;

import com.esbi.projectwebsocket.aiRequest.AiRequestService;
import com.esbi.projectwebsocket.aiRequest.ResultResponse;
import com.esbi.projectwebsocket.aiRequest.ResultUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * WebSocket服务
 *
 *
 * 直接双击websocet.html这个就可以。可以运行成
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    @Autowired
    AiRequestService aiRequestService;
    //存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public String onMessage(String message, @PathParam("sid") String sid) throws JSONException {
        System.out.print("\33[41;1m"+message+"\n\33[0m");//红色背景
        String s = processInput(message);
        System.out.print("\33[41;1m"+s+"\n\33[0m");//红色背景
        System.out.println("收到来自客户端：" + sid + "的信息:" + message);//这个是与原始的不能变
        return s;
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    public String processInput(String input) throws JSONException {
        String url = "http://112.111.7.68:13201/ele_bill";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "text/event-stream");
        headers.set("Authorization", "Basic YmFja2VuZF9hY2NvdW50OmJhY2tlbmRfMjAyNDA1MzA=");
        //String requestBody = "{\"conversation_id\":\"1001012\",\"input\":\"上海中心大厦\",\"doc_content\":\"\"}";

        // 创建一个JSONObject来存储键值对
        JSONObject jsonObject = new JSONObject();
        // 向JSONObject中添加动态数据
        jsonObject.put("conversation_id","1001012");
        jsonObject.put("input", input);
        // 假设doc_content总是空的，这里直接设为""
        jsonObject.put("doc_content", "");
        String requestBody = jsonObject.toString();

        //System.out.print("\33[41;1m"+jsonObject+"\n\33[0m");//红色背景
        //System.out.print("\33[42;1m"+requestBody+"\n\33[0m");//红色背景
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        //System.out.println(response.getBody());//注释掉应该打印在控制台的信息
        String body = response.getBody();
        //不对数据做修改直接返回原始数据。
        String returnBody = extractAndCombineTexts(body);
        System.out.print("\33[41;1m"+returnBody+"\n\33[0m");//红色背景
        System.out.println("request:"+input);
        //return body ;
        return returnBody ;
    }




    public static String extractAndCombineTexts(String input) {
        Pattern pattern = Pattern.compile("\"text\": \"([^\"]+)\"");
        Matcher matcher = pattern.matcher(input);
        StringBuilder combinedText = new StringBuilder();
        while (matcher.find()) {
            String text = matcher.group(1);
            if (!text.contains("\n") &&!text.contains("\\n")) {
                combinedText.append(text);
            }
        }
        return combinedText.toString();
    }





}
